// base
import Taro, { Component } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import { AtActionSheet } from 'taro-ui'
// redux
import { connect } from '@tarojs/redux'
import { DOREQUESTSTARTPAGE } from './store/actions/pagestartpage'
import { UPDATEPAGESTARTPAGE } from './store/types/pagestartpage'
import { UPDATEUSERINFO, CLEARUSERINFO } from '../../store/types/userinfo'
import {
  getZhichuBUserInfo,
  getZhichuUserInfo,
  updateCompanyId
} from '../../store/actions/userinfo'
// less
import './index.less'

// componnet
import NetworkError from '../../components/taro-ui/network-error'
// libs
import { switchTab } from '../../crossplatform/apiservice/navigate'
import { setNavigationBarColor } from '../../crossplatform/apiservice/tabbar'
import pagejumplist from '../../configuration/pagejumplist.json'
import StartImg from '../../static/images/startimg.png'
import { setStorageSync, getStorageSync, removeStorageSync } from '../../crossplatform/apiservice/storage'
import SwitchRole from '../../components/page-components/switch-role/index'
import wxLogin from '../../util/wxLogin'
import { insertRecommendHistory } from '../../service/wechat-pay'
import IMController from '../../util/wy_im'
import { getUpdateManager, canIUse } from '../../crossplatform/apiservice/updateManager'
import { showModal } from '../../crossplatform/apiservice/toast'

const mapActiontoProps = dispatch => ({
  updateState (payload) {
    dispatch({
      type: UPDATEPAGESTARTPAGE,
      payload: {
        ...payload
      }
    })
  },
  updateUserState (payload) {
    dispatch({
      type: UPDATEUSERINFO,
      payload: {
        ...payload
      }
    })
  },
  clearUserState (payload) {
    dispatch({
      type: CLEARUSERINFO,
      payload: {
        ...payload
      }
    })
  },
  getZhichuUserInfo (payload) {
    return new Promise(resolve => {
      let promise = getZhichuUserInfo(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  getZhichuBUserInfo (payload) {
    return new Promise(resolve => {
      let promise = getZhichuBUserInfo(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  updateCompany () {
    dispatch(updateCompanyId())
  },
  dorequest () {
    return new Promise(resolve => {
      let promise = DOREQUESTSTARTPAGE()
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  }
})

@connect(
  ({ pagestartpage, userinfo, im }) => ({
    ...pagestartpage,
    ...userinfo,
    ...im
  }),
  mapActiontoProps
)
class StartPage extends Component {
  config = {
    navigationBarTitleText: ''
  }

  constructor (props) {
    super(props)
    this.state = {
      modalVisible: false
    }
  }

  componentWillMount () {
    // onLoad
    let userinfo = getStorageSync('userinfo')
    this.props.updateUserState({
      ...userinfo
    })
    setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#FFE400'
    })
    this.checkUpdate()
  }

  timer = null
  componentDidShow () {
    // onshow
    // removeStorageSync('userinfo')
    // this.props.clearUserState()
    this.wxLogin()
    this.timer = setTimeout(() => {
      clearTimeout(this.timer)
      this.bindRedirect()
      IMController.queryWrap()
    }, 2000)
  }
  componentWillUnmount () {
    // onUnload
    this.setState({
      modalVisible: false
    })
  }
  componentDidHide () {
    // onhide
    this.setState({
      modalVisible: false
    })
  }

  bindRedirect = () => {
    const { userId } = this.props
    this.setState({
      modalVisible: false
    })
    if (userId) {
      switchTab({
        url: pagejumplist['job-view'].path
      })
    } else {
      this.setState({
        modalVisible: true
      })
    }
  }

  wxLogin = () => {
    wxLogin.props = this.props
    wxLogin.doLogin().then(data => {
      if (this.$router.params.scene) {
        insertRecommendHistory({
          companyId: this.$router.params.scene,
          openid: this.props.openId
        }).then(date => {
          console.log(date, '调用成功')
        })
      }
      wxLogin.getArchiveInfo()
    })
  }

  changeUserRole = () => {
    this.setState({
      modalVisible: true
    })
  }

  confirmSwitchRole = (currentRole = []) => {
    let role = 'personal'
    currentRole.forEach(item => {
      if (item.check) {
        role = item.role
      }
    })
    if (role == 'personal') {
      switchTab({
        url: pagejumplist['job-view'].path
      })
    } else {
      setStorageSync('goSetting', 1)
      switchTab({
        url: pagejumplist['self-center'].path
      })
    }
  }

  checkUpdate = () => {
    // 检查微信新版本
    if (canIUse('getUpdateManager')) {
      const updateManager = getUpdateManager()
      updateManager.onCheckForUpdate(res => {
        // 请求完新版本信息的回调
        console.log(res.hasUpdate)
      })
      updateManager.onUpdateReady(() => {
        // showModal({
        //   title: '更新提示',
        //   content: '新版本已经准备好，是否重启应用？',
        //   success: res => {
        //     if (res.confirm) {
        //       // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
        //       updateManager.applyUpdate()
        //     } else if (res.cancel) {
        //       // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
        //       updateManager.applyUpdate()
        //       // return false
        //     }
        //   }
        // })
      })
      updateManager.onUpdateFailed(() => {
        // 新的版本下载失败
        showModal({
          title: '升级失败',
          content: '新版本下载失败，请检查网络！',
          showCancel: false
        })
      })
    }
  }

  render () {
    const { modalVisible } = this.state
    return (
      <View className="StartPage_id66974">
        <NetworkError visible={this.props.networkerror} />
        <View className={`StartPage_id66974Wrap ${this.props.networkerror ? 'hide' : ''}`}>
          {/* <StartupPage /> */}
          <Image className="start-image" src={StartImg} mode="widthFix" />
        </View>

        <View className="mask" />
        <AtActionSheet isOpened={modalVisible}>
          <SwitchRole role="all" onConfirm={this.confirmSwitchRole} />
        </AtActionSheet>
      </View>
    )
  }
}

export default StartPage
